package com.example.hello_world.sharedpreference;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hello_world.R;

import org.w3c.dom.Text;

public class train_sharedpreferences extends AppCompatActivity implements View.OnClickListener {

    private TextView text;
    private Button Btn_save,Btn_read;
    private EditText Et;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train_sharedpreferences);
        text=findViewById(R.id.show_text);
        Btn_save=findViewById(R.id.save_button);
        Btn_read=findViewById(R.id.read_button);
        Et=findViewById(R.id.edit);

        Btn_save.setOnClickListener(this);
        Btn_read.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_button:
                String msg=Et.getText().toString();
//                SharedPreferences sharedPreferences=getSharedPreferences("table01",MODE_PRIVATE);
//                SharedPreferences.Editor editor=sharedPreferences.edit();
                SharedPreferences.Editor ed=getSharedPreferences("table01",MODE_PRIVATE).edit();
                ed.putString("string",msg);
                boolean isSaved=ed.commit();
                if(isSaved){
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.read_button:
                SharedPreferences sp=getSharedPreferences("table01",MODE_PRIVATE);
                String st=sp.getString("string","无");
                text.setText(st);
                break;
        }
    }
}